package com.cssw.fyzb.busi.api.pay;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.busi.service.pay.PayService;
import com.cssw.fyzb.busi.util.MapUtil;
import com.cssw.fyzb.core.exception.BizException;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.dbframe.kit.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: chenchao
 * @Date: 2020/7/14 22:10
 */

@Function(description = "微信异步通知校验", parameters = {
        @Parameter(name = "params", type = Type.String, description = "参数", required = true),
})
@Component
public class WxVerifyNotify implements Action {

    private static final Logger logger = LoggerFactory.getLogger(WxVerifyNotify.class);
    @Autowired
    private TpsClient tpsClient;
    @Autowired
    private PayService payService;

    @Override
    public Response execute(Request request) throws Exception {
        String params = request.getString("params");
        logger.info(" WxVerifyNotify >>> " + params);


        if (!verifyNotify(params)) {
            logger.error(" WxVerifyNotify error>>> " + params);
            return Response.fail("校验失败");
        }

        Map param = JSON.parseObject(params, Map.class);

        String returnCode = MapUtil.getString(param, "return_code");
        if (StrKit.isBlank(returnCode) || !"SUCCESS".equals(returnCode)) {
            return Response.fail("未支付成功");
        }

        String tradeNo = MapUtil.getString(param, "out_trade_no");

        try {
            // 回调业务处理
            payService.afterPayBusi(tradeNo);
            return Response.success();

        } catch (BizException biz) {
            logger.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getErrMsg(), biz.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        }

    }


    private boolean verifyNotify(String params) {
        Request request = new Request("WxVerifyNotify");
        request.setParameter("params", params);
        Response response = tpsClient.send(request);
        return response.isSuccess();

    }


}